package io.renren.modules.business.util;

import io.renren.common.utils.R;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Objects;

/**
 * 文件上传与下载工具类
 *
 * @author liao mengqing
 */
@RestController
@RequestMapping("business/file")
public class FileUploadUtils {

    public static final String FILE_PATH = new FilePathUtils().getCoverPath();

    /**
     * 文件上传
     * @param files
     * @param request
     * @return
     */
    @PostMapping("/upload")
    public Object uploadFile(@RequestParam("file") List<MultipartFile> files, HttpServletRequest request) {
        //被保存文件路径
        String UPLOAD_FILES_PATH = FILE_PATH + System.currentTimeMillis() +"\\";
        if (Objects.isNull(files) || files.isEmpty()) {
            return R.error("文件为空，请重新上传");
        }
        for(MultipartFile file : files){
            String fileName = file.getOriginalFilename();
            String result = null;
            try {
                result = upLoad(UPLOAD_FILES_PATH, fileName, file);
                // 保存文件
            } catch (Exception e) {
                e.printStackTrace();
            }
            if (!result.equals("true")) {
                R.error(result);
            }
            UPLOAD_FILES_PATH += fileName;
            // 构建附件类
        }
        return R.ok("文件上传成功")
                .put("attachEntity",UPLOAD_FILES_PATH);
    }

    /**
     * 文件下载
     */
    @PostMapping(value = "/download")
    public void downloadFile(final HttpServletResponse response, final HttpServletRequest request) {
        String filePath = request.getParameter("filePath");
        download(response, filePath);
    }

    /**
     * 新建文件到指定路径
     * @param UPLOAD_FILES_PATH
     * @param fileName
     * @param file
     * @return
     * @throws Exception
     */
    public static String upLoad (String UPLOAD_FILES_PATH, String fileName, MultipartFile file) throws Exception {
        if(file.isEmpty()){
            return "文件为空";
        }else{
            File dest = new File(UPLOAD_FILES_PATH  + "/" +  fileName );
            if(!dest.getParentFile().exists()){ //判断文件父目录是否存在
                dest.getParentFile().mkdirs();
            }
            file.transferTo(dest);
        }
        return "true";
    }

    /**
     * 文件下载
     * @param response
     * @param realPath
     */
    public static void download(final HttpServletResponse response, String realPath) {
        File file = new File(realPath);
        if (file.exists()) {
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            // 下载文件能正常显示中文
//			try {
//				response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
//			} catch (UnsupportedEncodingException e) {
//				e.printStackTrace();
//			}
            // 实现文件下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
